package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbUser;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageOrderVo;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
* @author 28242
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-04-21 16:19:57
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{


    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IUserService iUserService;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    HttpServletRequest request;


    /**
     * 根据id查询订单
     * @param id
     * @return
     */
    @Override
    public R getOrderById(Integer id) {

        TbOrder tbOrder = tbOrderMapper.selectById(id);

        if (tbOrder==null){
            return R.ERROR(404,"该订单不存在");
        }

//        String url="http://localhost:9001/user/index/getUserById/"+tbOrder.getUserId();
//        R r = restTemplate.postForObject(url,null,R.class);


        R r = iUserService.getUserById(tbOrder.getUserId());
        if (r.getCode()!=200){
            return r;
        }
        String u= JSON.toJSONString(r.getData());

        TbUser tbUser = JSON.parseObject(u, TbUser.class);

        tbOrder.setTbUser(tbUser);
        return R.OK(tbOrder);
    }

    @Override
    public R getOrderList(PageOrderVo pageOrderVo) {

        Page<TbOrder> page = new Page<>(pageOrderVo.getPageNum(), pageOrderVo.getPageSize());

//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotEmpty(pageOrderVo.getKeyWord())){
//            wrapper.lambda().eq(TbOrder::getOrderId,pageOrderVo.getKeyWord());
//        }
//        if (pageOrderVo.getStatus()!=null){
//            wrapper.lambda().eq(TbOrder::getOrderStatus,pageOrderVo.getStatus());
//        }
//
//        //排序
//        wrapper.lambda().orderByDesc(TbOrder::getOrderId);
//

        //分页查询
        Page<TbOrder> tbOrderPage=tbOrderMapper.getOrderList(page,pageOrderVo.getKeyWord(),pageOrderVo.getStatus());


        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProd> tbProdList) {

        String token = request.getHeader("token");

        if (token==null){
            return R.ERROR(404,"请用户先登录");
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);



        //生成订单
        TbOrder tbOrder = new TbOrder();

        tbOrder.setOrderStatus(0);

        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        code+=RandomUtil.randomNumbers(4);

        tbOrder.setOrderCode(code);
        tbOrder.setUserId(userId);
        tbOrder.setCreateTime(new Date());

        double amount=0.0;
        Integer num=0;
        for (TbProd tbProd : tbProdList) {
            amount= amount+ tbProd.getBuyNum() * tbProd.getProdPrice();
            num+=tbProd.getBuyNum();
        }

        tbOrder.setAmount(amount);
        tbOrder.setProdCount(num);

        tbOrderMapper.insert(tbOrder);

        //保存订单
        for (TbProd tbProd : tbProdList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setProdId(tbProd.getProdId());
            tbOrderDetail.setBuyNum(tbProd.getBuyNum());
            tbOrderDetail.setProdPrice(tbProd.getProdPrice());
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetailMapper.insert(tbOrderDetail);
        }


        return R.OK();
    }
}




